package com.gks.controller;

import ch.qos.logback.core.util.StringUtil;
import com.gks.entities.Article;
import com.gks.entities.resp.Result;
import com.gks.entities.vo.ArticleVo;
import com.gks.service.ArticleService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("article")
public class ArticleController {

    @Resource
    private ArticleService articleService;

    @GetMapping("/list")
    public Result getArticleList() {
        try {
            List<ArticleVo> articles = articleService.searchArticles(null, null);
            return Result.success("获取文章列表成功", articles);
        } catch (Exception e) {
            return Result.error("获取文章列表失败：" + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public Result getArticle(@PathVariable Integer id) {
        try {
            ArticleVo article = articleService.selectArticle(id);
            if (article == null) {
                return Result.error("文章不存在");
            }
            return Result.success("获取文章成功", article);
        } catch (Exception e) {
            return Result.error("获取文章失败：" + e.getMessage());
        }
    }

    @PostMapping
    public Result addArticle(@RequestBody Article article) {
        try {
            if (StringUtil.isNullOrEmpty(article.getTitle()) 
                || StringUtil.isNullOrEmpty(article.getContent())
                || StringUtil.isNullOrEmpty(article.getSummary())
                || StringUtil.isNullOrEmpty(article.getCategory())) {
                return Result.error("请填写完整信息");
            }
            articleService.addArticle(article);
            return Result.success("添加文章成功");
        } catch (Exception e) {
            return Result.error("添加文章失败：" + e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public Result updateArticle(@PathVariable Integer id, @RequestBody Article article) {
        try {
            article.setId(id);
            articleService.updateArticle(article);
            return Result.success("更新文章成功");
        } catch (Exception e) {
            return Result.error("更新文章失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Result deleteArticle(@PathVariable Integer id) {
        try {
            articleService.deleteArticle(id);
            return Result.success("删除文章成功");
        } catch (Exception e) {
            return Result.error("删除文章失败：" + e.getMessage());
        }
    }
}


